package com.headsen.springboot.excel.controller;


import com.headsen.springboot.excel.controller.model.ExcelData;
import com.headsen.springboot.excel.service.ExcelService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@RestController
public class HelloController {

    @RequestMapping(value = "/hello")
    public String hello() {
        return "Hello";
    }


    @RequestMapping(value = "/export")
    public void export(HttpServletResponse resp) {
        try {
            ExcelData data = ExcelService.buildTestData();
            XSSFWorkbook sheets = ExcelService.scanTemplateAndFill(data);

            resp.setContentType("application/octet-stream");
            resp.setCharacterEncoding("utf-8");
//            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xlsx");

            try (OutputStream os = resp.getOutputStream()) {
                sheets.write(os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
